package collection;

import leetcode.Hot100.LRUCache1;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Cheng Jun
 * Description: LinkedHashMap 源码学习
 * A special constructor is provided to create a linked hash map whose order of iteration is the order in which
 * its entries were last accessed, from least-recently accessed to most-recently (access-order).
 * This kind of map is well-suited to building LRU caches.
 * @version 1.0
 * @date 2021/11/16 21:51
 * @see LinkedHashMap
 * @see LRUCache1
 */
public class LinkedHashMapLRUStudy {

    public static void main(String[] args) {
        LRU<String, String> shopInfoLRu = new LRU<>(4);
        // 源码put方法，返回的值是 null
        String put = shopInfoLRu.put("HUAWEI", "华为全球第一");
        shopInfoLRu.put("XIAOMI", "小米中国第一");
        shopInfoLRu.put("OPPO", "OPPO不咋滴");
        shopInfoLRu.put("APPLE", "苹果");
        System.out.println(shopInfoLRu.get("HUAWEI"));
        System.out.println(shopInfoLRu.get("XIAOMI"));
    }

    static class LRU<K, V> extends LinkedHashMap<K, V> {
        private int capacity;

        public LRU(int capacity) {
            // 扩容因子 最好设置成1，避免浪费空间
            super(capacity, 1f, true);
            this.capacity = capacity;
        }

        @Override
        public V get(Object key) {
            return super.get(key);
        }

        @Override
        public V put(K key, V value) {
            return super.put(key, value);
        }

        /**
         * 实现移除 最近最少使用的元素 的逻辑
         *
         * @param eldest
         * @return boolean
         * @author Cheng Jun
         * @date 2021/11/17 11:04
         */
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > capacity;
        }
    }
}
